package com.lvy.hczn.front.business.service.impl;

import java.nio.charset.StandardCharsets;
import java.util.List;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvy.hczn.front.business.mapper.WarehouseBoxEntryMapper;
import com.lvy.hczn.front.business.service.WarehouseBoxEntryService;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.common.utils.DateUtils;
import com.lvy.hczn.front.system.domain.business.GoodsBox;
import com.lvy.hczn.front.system.domain.business.Warehouse;
import com.lvy.hczn.front.system.domain.business.WarehouseBoxEntry;
import com.lvy.hczn.front.system.service.WarehouseService;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lvy.hczn.front.common.core.text.Convert;

/**
 * 货箱入库单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-23
 */
@Service
public class WarehouseBoxEntryServiceImpl extends ServiceImpl<WarehouseBoxEntryMapper, WarehouseBoxEntry> implements WarehouseBoxEntryService {
    @Autowired
    private WarehouseBoxEntryMapper warehouseBoxEntryMapper;

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private WarehouseService warehouseService;

    /**
     * 查询货箱入库单
     *
     * @param id 货箱入库单主键
     * @return 货箱入库单
     */
    @Override
    public WarehouseBoxEntry selectWarehouseBoxEntryById(String id) {
        return warehouseBoxEntryMapper.selectWarehouseBoxEntryById(id);
    }

    /**
     * 查询货箱入库单列表
     *
     * @param warehouseBoxEntry 货箱入库单
     * @return 货箱入库单
     */
    @Override
    public List<WarehouseBoxEntry> selectWarehouseBoxEntryList(WarehouseBoxEntry warehouseBoxEntry) {
        return warehouseBoxEntryMapper.selectWarehouseBoxEntryList(warehouseBoxEntry);
    }

    /**
     * 新增货箱入库单
     *
     * @param warehouseBoxEntry 货箱入库单
     * @return 结果
     */
    @Override
    public int insertWarehouseBoxEntry(WarehouseBoxEntry warehouseBoxEntry) {
        if (StrUtil.isEmpty(warehouseBoxEntry.getBoxEntryCode())) {
            warehouseBoxEntry.setBoxEntryCode(IdUtil.fastSimpleUUID());
        }
        int result = warehouseBoxEntryMapper.insert(warehouseBoxEntry);
        if (result > 0) {
            ParamInfo<WarehouseBoxEntry> info = new ParamInfo<>();
            info.setWarehouseCode(warehouseBoxEntry.getWarehouseCode());
            info.setData(warehouseBoxEntry);
            try {
                //空箱入库发送到中台，告知仓库入库有多少空箱
                producerUtil.sendAsyncMsg(MqConstants.TOPIC_WAREHOUSE_EMPTY_OUT_ENTRY_BOX, null, JSON.toJSONString(info).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
                warehouseBoxEntry.setTreated(true);
                warehouseBoxEntryMapper.updateById(warehouseBoxEntry);
            } catch (Exception e) {
                throw new UtilException(e.getMessage());
            }
        }
        return result;
    }

    /**
     * 空箱放到仓库，同步到数据中心，然后转发平台
     *
     * @param warehouseBoxEntry
     * @return void
     * @author yw
     * @date 2023-11-24 17:22:28
     */
    @Override
    public void syncToDataTransmit(WarehouseBoxEntry warehouseBoxEntry) {
        if (warehouseBoxEntry == null) {
            List<WarehouseBoxEntry> list = super.list(Wrappers.<WarehouseBoxEntry>lambdaQuery().eq(WarehouseBoxEntry::getTreated, false));
            if (!list.isEmpty()) {
                ParamInfo<WarehouseBoxEntry> info = new ParamInfo<>();
                info.setWarehouseCode(warehouseBoxEntry.getWarehouseCode());
                info.setList(list);
                try {
                    producerUtil.sendAsyncMsg(MqConstants.TOPIC_WAREHOUSE_EMPTY_OUT_ENTRY_BOX, null, JSON.toJSONString(info).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
                    list.forEach(item -> {
                        item.setTreated(true);
                    });
                    super.updateBatchById(list);
                } catch (Exception e) {
                    throw new UtilException("信息发送异常：{}", e);
                }
            }
        } else {
            insertWarehouseBoxEntry(warehouseBoxEntry);
        }
    }

    /**
     * 初始化空箱单据
     *
     * @param goodsBox
     * @param warehouseBoxEntry
     * @param type              入库类型（0：空箱入库，不入仓库货架；1:出库）
     * @param overType          0清箱入库,1采购入库,2调拨入库,3报损入库,4其他入库,5取箱出库,6调拨出库7其他出库
     * @param boxEntryCode      单号
     * @return void
     * @author yw
     * @date 2023-11-24 20:33:02
     */
    @Override
    public void initWarehouseBoxEntryByGoodsBox(GoodsBox goodsBox, WarehouseBoxEntry warehouseBoxEntry, Integer type, Integer overType, String boxEntryCode) {
        Warehouse warehouse = warehouseService.selectLocalWarehouseFront();
        if (warehouse != null) {
            if (StrUtil.isEmpty(boxEntryCode)) {
                warehouseBoxEntry.setBoxEntryCode(IdUtil.fastSimpleUUID());
            } else {
                warehouseBoxEntry.setBoxEntryCode(boxEntryCode);
            }
            warehouseBoxEntry.setBoxCode(goodsBox.getBoxCode());
            warehouseBoxEntry.setWarehouseCode(warehouse.getWarehouseCode());
            warehouseBoxEntry.setType(type);
            warehouseBoxEntry.setOverType(overType);
            warehouseBoxEntry.setBoxCode(goodsBox.getBoxCode());
            warehouseBoxEntry.setGoodsBoxSpecCode(goodsBox.getGoodsBoxSpecId());
            warehouseBoxEntry.setTotal(1);
            warehouseBoxEntry.setBoxProducer(goodsBox.getCreateBy());
            warehouseBoxEntry.setTreated(false);
        }
    }

    /**
     * 修改货箱入库单
     *
     * @param warehouseBoxEntry 货箱入库单
     * @return 结果
     */
    @Override
    public int updateWarehouseBoxEntry(WarehouseBoxEntry warehouseBoxEntry) {
        return warehouseBoxEntryMapper.updateById(warehouseBoxEntry);
    }

    /**
     * 批量删除货箱入库单
     *
     * @param ids 需要删除的货箱入库单主键
     * @return 结果
     */
    @Override
    public int deleteWarehouseBoxEntryByIds(String ids) {
        if (StrUtil.isEmpty(ids)) {
            throw new UtilException("参数为空");
        }
        String[] arr = Convert.toStrArray(ids);
        for (String id : arr) {
            super.removeById(id);
        }
        return arr.length;
    }

    /**
     * 删除货箱入库单信息
     *
     * @param id 货箱入库单主键
     * @return 结果
     */
    @Override
    public int deleteWarehouseBoxEntryById(String id) {
        if (StrUtil.isEmpty(id)) {
            throw new UtilException("ID为空");
        }
        super.removeById(id);
        return 1;
    }
}
